import React from 'react';
import { Card, Table, Button, Form, Input, Space, Modal, Pagination, Select, message } from 'antd';
import dayjs from 'dayjs';

// AD集团（广告分组管理）——模仿 admin-web 的 AdvertGroup.vue
export default function AdvertGroup() {
  // 搜索
  const [searchForm] = Form.useForm();
  const [search, setSearch] = React.useState({ name: '' });

  // 字典：展示位置（模拟 gp_show_type）
  const [showType, setShowType] = React.useState([
    { label: '全部设备', value: 0 },
    { label: '首页轮播', value: 1 },
    { label: '详情页顶部', value: 2 },
    { label: '底部Banner', value: 3 },
  ]);

  // 列表与分页
  const [loading, setLoading] = React.useState(false);
  const [pageIndex, setPageIndex] = React.useState(1);
  const [pageSize, setPageSize] = React.useState(10);
  const [advertGroupList, setAdvertGroupList] = React.useState(() => ([
    { id: 1, userName: 'Alice', name: '节日活动组', notes: '节日类广告集合', display: '展示', createTime: '2025-09-01 10:00', showTypeValues: [1,3] },
    { id: 2, userName: 'Bob', name: '品牌宣传组', notes: '品牌故事与宣传', display: '展示', createTime: '2025-09-10 09:20', showTypeValues: [2] },
  ]));

  const filtered = React.useMemo(() => {
    let list = advertGroupList;
    if (search.name) list = list.filter(i => String(i.name || '').includes(search.name));
    return list;
  }, [advertGroupList, search]);

  const pageData = React.useMemo(() => {
    const start = (pageIndex - 1) * pageSize;
    return filtered.slice(start, start + pageSize);
  }, [filtered, pageIndex, pageSize]);

  // 新增/编辑弹窗
  const [dialogAdvertGroup, setDialogAdvertGroup] = React.useState(false);
  const [groupForm] = Form.useForm();
  const [editingRow, setEditingRow] = React.useState(null);

  const addAdvertGroup = () => {
    setEditingRow(null);
    groupForm.resetFields();
    setDialogAdvertGroup(true);
  };
  const editAdvertGroup = (row) => {
    setEditingRow(row);
    setDialogAdvertGroup(true);
    groupForm.setFieldsValue({ name: row.name, notes: row.notes, display: row.display });
  };
  const saveAdvertGroup = async () => {
    const values = await groupForm.validateFields();
    if (editingRow) {
      setAdvertGroupList(prev => prev.map(i => (i.id === editingRow.id ? { ...i, ...values } : i)));
      message.success('分组已更新');
    } else {
      const id = Math.max(0, ...advertGroupList.map(i => i.id)) + 1;
      const newItem = { id, userName: 'Admin', createTime: dayjs().format('YYYY-MM-DD HH:mm'), showTypeValues: [], ...values };
      setAdvertGroupList(prev => [newItem, ...prev]);
      message.success('分组已添加');
    }
    setDialogAdvertGroup(false);
  };

  // 分组关联（配置展示位置）弹窗
  const [dialogAdvertGroupRela, setDialogAdvertGroupRela] = React.useState(false);
  const [relaRow, setRelaRow] = React.useState(null);
  const [relaValues, setRelaValues] = React.useState([]);

  const advertConfig = (row) => {
    setRelaRow(row);
    setRelaValues(row.showTypeValues || []);
    setDialogAdvertGroupRela(true);
  };
  const saveAdvertConfig = () => {
    if (!relaRow) return;
    setAdvertGroupList(prev => prev.map(i => (i.id === relaRow.id ? { ...i, showTypeValues: relaValues } : i)));
    setDialogAdvertGroupRela(false);
    message.success('配置已保存');
  };

  const deleteAdvertGroup = (row) => {
    Modal.confirm({
      title: '删除确认',
      content: `确定删除分组「${row.name}」吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        setAdvertGroupList(prev => prev.filter(i => i.id !== row.id));
        message.success('删除成功');
      },
    });
  };

  const onSubmitSearch = async () => {
    const values = await searchForm.validateFields();
    setSearch(values);
    setPageIndex(1);
  };
  const resetSearch = () => {
    searchForm.resetFields();
    setSearch({ name: '' });
    setPageIndex(1);
  };

  const columns = [
    { title: '用户昵称', dataIndex: 'userName', width: 250, align: 'center' },
    { title: '分组名称', dataIndex: 'name', width: 200, align: 'center' },
    { title: '备注', dataIndex: 'notes', align: 'center' },
    { title: '创建时间', dataIndex: 'createTime', width: 160, align: 'center' },
    {
      title: '操作', fixed: 'right', width: 240, align: 'center',
      render: (_, row) => (
        <Space>
          <Button size="small" onClick={() => editAdvertGroup(row)}>编辑</Button>
          <Button size="small" type="warning" onClick={() => advertConfig(row)}>广告配置</Button>
          <Button size="small" danger onClick={() => deleteAdvertGroup(row)}>删除</Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="adverts-group">
      {/* 搜索与新增 */}
      <div className="el-search vue-top-padding" style={{ marginBottom: 12 }}>
        <div className="el-left" style={{ display: 'inline-block' }}>
          <Button type="primary" onClick={addAdvertGroup}>新增分组</Button>
        </div>
        <div className="el-right" style={{ float: 'right' }}>
          <Form form={searchForm} layout="inline" initialValues={search}>
            <Form.Item name="name">
              <Input placeholder="分组名称" allowClear />
            </Form.Item>
            <Form.Item>
              <Space>
                <Button type="primary" onClick={onSubmitSearch}>搜索</Button>
                <Button onClick={resetSearch}>重置</Button>
              </Space>
            </Form.Item>
          </Form>
        </div>
      </div>

      {/* 表格 */}
      <Card className="vue-padding radius">
        <Table
          rowKey={(r) => r.id}
          loading={loading}
          dataSource={pageData}
          columns={columns}
          pagination={false}
          scroll={{ y: 638 }}
          bordered
        />

        <div style={{ marginTop: 12, display: 'flex', justifyContent: 'center' }}>
          <Pagination
            current={pageIndex}
            pageSize={pageSize}
            total={filtered.length}
            showSizeChanger
            onChange={(pi, ps) => { setPageIndex(pi); setPageSize(ps); }}
          />
        </div>
      </Card>

      {/* 新增/编辑分组弹窗 */}
      <Modal
        title={editingRow ? '编辑分组' : '新增分组'}
        open={dialogAdvertGroup}
        onCancel={() => setDialogAdvertGroup(false)}
        onOk={saveAdvertGroup}
        okText="保存"
        cancelText="取消"
      >
        <Form form={groupForm} layout="vertical">
          <Form.Item label="分组名称" name="name" rules={[{ required: true, message: '请输入分组名称' }]}> 
            <Input placeholder="请输入分组名称" />
          </Form.Item>
          <Form.Item label="备注" name="notes"> 
            <Input.TextArea rows={3} placeholder="备注" />
          </Form.Item>
          <Form.Item label="显示文案" name="display"> 
            <Input placeholder="显示文案（可选）" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 广告配置弹窗（分组关联展示位置） */}
      <Modal
        title="广告配置"
        open={dialogAdvertGroupRela}
        onCancel={() => setDialogAdvertGroupRela(false)}
        onOk={saveAdvertConfig}
        okText="保存"
        cancelText="取消"
      >
        <div style={{ marginBottom: 8 }}>请选择该分组关联的展示位置：</div>
        <Select
          mode="multiple"
          value={relaValues}
          style={{ width: '100%' }}
          onChange={setRelaValues}
          options={showType.map(s => ({ label: s.label, value: s.value }))}
          placeholder="请选择展示位置（可多选）"
        />
      </Modal>
    </div>
  );
}